import * as MobileAction from '@/api/mobile'
import {Loading} from "element-ui";
const isPro = process.env.NODE_ENV === 'production'

export function judgeMobile () {
  const ua = navigator.userAgent
  const ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
    isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
    isAndroid = ua.match(/(Android)\s+([\d.]+)/)
  return isIphone || isAndroid;
}

/**
 * @description 判断字符串或数字为空，可以为0
 * @param {String, Number} value
 */
export function isBlank (value) {
  try {
    const _value = value.toString()
    return !_value
  } catch (error) {
    return true
  }
}

export function setCookie (cname, val, day) {
  const d = new Date()
  d.setTime(d.getTime() + (day * 24 * 60 * 60 * 1000))
  const expires = "expires=" + d.toGMTString()
  document.cookie = cname + "=" + val + "; " + expires;
}

export function getCookie (cname) {
  let name = cname + "="
  const ca = document.cookie.split(';')
  for (let i=0; i < ca.length; i++) {
    let c = ca[i].trim()
    if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
  }
  return ""
}

export function delCookie (name) {
  const exp = new Date();
  exp.setTime(exp.getTime() - 1);
  const cval = getCookie(name);
  if (cval !== null)
    document.cookie= name + "=" + cval + ";expires=" + exp.toGMTString();
}


export function isMobile(){
  let info = navigator.userAgent
  let agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPod", "iPad"]
  for (let i = 0; i < agents.length; i++) {
    if (info.indexOf(agents[i]) >= 0) return true
  }
  return false
}

// 获取url参数
export function getQueryVariable(name) {
  const reg = new RegExp("(^|&)" + name+ "=([^&]*)(&|$)", "i")
  const result = window.location.search.substr(1).match(reg)
  if (result !== null ){
    return decodeURI(result[2])
  } else {
    return null
  }
}

// 调用方式
// 参数一： src
// 参数二： 图片名称，可选
export function downloadImage(src, imgName = '图片') {
  // 生成一个 a 标签
  const a = document.createElement("a");
  a.download = imgName
  a.style.display = "none";
  const image = new Image();
  image.src = src + "?v=" + Math.random();
  image.crossOrigin = "*";
  image.onload = () => {
    const base64 = getBase64Images(image);
    a.href = base64;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
}

function getBase64Images(image) {
  const canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  const context = canvas.getContext("2d");
  context.drawImage(image, 0, 0, image.width, image.height);
  const url = canvas.toDataURL("image/png", 0);
  return url;
}

// 微信网页授权
export async function jumpToGetAuth (cb) {
  const code = sessionStorage.getItem('code')
  if (!code) {
    const appid = isPro ? 'wx81402428922d938c' : 'wx8a2ecdb02576162b'
    const redirectUrl = isPro? 'https://cbmm.yw.gov.cn' : 'http://dev3.keyougufen.com'
    const urlParam = location.href.split('?')[1]
    const origin = 'https://open.weixin.qq.com/connect/oauth2/authorize'
    const url = `${origin}?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=${urlParam}#wechat_redirect`
    location.href = url
  } else {
    // 此处已获取code, 调用后端接口登录
    const res = await MobileAction.code2token({
      code,
      client_id: 'mobile',
      client_secret: 'mobile',
      grant_type: 'wechat',
    })
    sessionStorage.removeItem('code')
    if (res) cb(res)
  }
}

// 支付宝网页授权
export async function getAliAuth (cb) {
  // eslint-disable-next-line
  ap.getAuthCode ({
    appId: '2021002147690645'
  }, async function (data){
    localStorage.setItem('authcode', JSON.stringify(data))
    // eslint-disable-next-line
    if (!data.authCode) return
    const res = await MobileAction.code2token({
      code: data.authCode,
      client_id: 'mobile',
      client_secret: 'mobile',
      grant_type: 'alipay'
    })
    if (res) cb(res)
  })
}

export function getCarQRCodeMix(bg, url, no) {
  return {
    'base': {
      'backgroundImg': bg,
      'width': 800,
      'height': 800,
      'quality': 1,
      'fileType': 'jpeg'
    },
    'dynamic': [
      {
        'type': 1,
        'position': {
          'x': 200,
          'y': 150
        },
        'size': {
          'dWidth': 400,
          'dHeight': 400
        },
        'imgUrl': url
      },
      {
        'type': 2,
        'position': {
          'x': 400,
          'y': 625
        },
        'style': {
          'textAlign': 'center',
          'fontSize': 64,
          'color': '#fff',
          'fontWeight': '500'
        },
        // 'text': no
      }
    ]
  }
}

export function getCompanyQRCodeMix(bg, url, name, address) {
  return {
    'base': {
      'backgroundImg': bg,
      'width': 800,
      'height': 800,
      'quality': 1,
      'fileType': 'jpeg'
    },
    'dynamic': [
      {
        'type': 1,
        'position': {
          'x': 170,
          'y': 130
        },
        'size': {
          'dWidth': 460,
          'dHeight': 460
        },
        'imgUrl': url
      },
      {
        'type': 2,
        'position': {
          'x': 400,
          'y': 660
        },
        'style': {
          'textAlign': 'center',
          'fontSize': 36,
          'color': '#fff',
          'fontWeight': '500'
        },
        'text': name
      }
    ]
  }
}


export function getCodeMix(bg, url, name, address) {
  return {
    'base': {
      'backgroundImg': bg,
      'width': 560,
      'height': 650,
      'quality': 1,
      'fileType': 'jpeg'
    },
    // 'dynamic': [
    //   {
    //     'type': 1,
    //     'position': {
    //       'x': 155,
    //       'y': 204
    //     },
    //     'size': {
    //       'dWidth': 250,
    //       'dHeight': 250
    //     },
    //     'imgUrl': url
    //   },
    //   {
    //     'type': 2,
    //     'position': {
    //       'x': 280,
    //       'y': 485
    //     },
    //     'style': {
    //       'textAlign': 'center',
    //       'fontSize': 18,
    //       'color': '#fff',
    //       'fontWeight': '500'
    //     },
    //     'text': name
    //   },
    //   {
    //     'type': 2,
    //     'position': {
    //       'x': 280,
    //       'y': 517
    //     },
    //     'style': {
    //       'textAlign': 'center',
    //       'fontSize': 14,
    //       'color': '#7AC1E4',
    //       'fontWeight': '500'
    //     },
    //     'text': address
    //   }
    // ]
  }
}

export  const  delayTimeScreen = ({time = 2000,message='消息加载中'})=>{
  const loading = Loading.service({
    lock: true,
    text: message,
    target:'#app',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  setTimeout(() => {
    loading.close();
  }, time);
}

 export  const  mapListLabel= ()=> {
  // 在这个地方去发送这个请求 模拟数据
   let  addressEq = ['金华','义乌','北京','上海','洪门'];
  return   addressEq.map(item => ({
     value: `${item}`,
     label: `${item}`,

   }))
 }

